package com.hydl.power.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hydl.power.mapper.*;
import com.hydl.power.pojo.*;
import com.hydl.power.service.DeviceService;
import com.hydl.power.service.SendOrdersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private PowerRoomMapper powerRoomMapper;
    @Autowired
    private OrderDeliveryMenuMapper orderDeliveryMenuMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IncomingCabinetMapper incomingCabinetMapper;

    @Autowired
    private LoopTypeMapper loopTypeMapper;

    @Autowired
    private PowerdataMapper powerdataMapper;

    @Autowired
    private WaterInvasionMapper waterInvasionMapper;

    @Autowired
    private VoltageMapper voltageMapper;

    @Autowired
    private GatewayMapper gatewayMapper;

    @Autowired
    private TemperatureDeviceMapper temperatureDeviceMapper;

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;

    @Autowired
    private SendOrdersService sendOrdersService;


    /**
     * 设备列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Device> selectDevice(Integer pageNum, Integer pageSize, String projectId) {
        List<Device> list = deviceMapper.getAllDevice(pageNum,pageSize,projectId);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Device> getAll(Integer pageNum, Integer pageSize) {
        List<Device> list = deviceMapper.getAll(pageNum,pageSize);
        return new PageInfo<>(list);
    }

    @Override
    public int addDevice(String deviceName,String areaId,String projectId,String powerRoomId,String serialNumber,
                         String gatewaySn) {
        Device device = new Device();
        device.setDeviceName(deviceName);
        device.setAreaId(areaId);
        device.setProjectId(projectId);
        device.setPowerRoomId(powerRoomId);
        device.setSerialNumber(serialNumber);
        device.setGatewaySn(gatewaySn);


        PowerRoom powerRoom = powerRoomMapper.selectByRoomId(powerRoomId);
        Project project = projectMapper.queryProjectByProId(projectId);
        City city = cityMapper.queryCityByCityId(areaId);
        device.setAreaName(city.getCityName());
        device.setPowerRoomName(powerRoom.getRoomName());
        device.setNavId(project.getProjectName());
        device.setTableName(project.getTableName());
        device.setFlag(1);
        return deviceMapper.insertInto(device);
    }

    @Override
    public List<PowerRoom> queryByNavId(String navId) {
        return powerRoomMapper.selectNavbarByNavId(navId);
    }

    @Override
    public int deleteNaviceById(Integer id) {
            return deviceMapper.deleteById(id);
    }

    @Override
    public Device getDeviceById(Integer id) {
        return deviceMapper.selectById(id);
    }

    @Override
    public int updateDeviceById(String deviceName,String deviceAddress,String deviceMessageAddress,String commonalityDdress,String aisle,Integer id,String serialNumber) {
        Device device = deviceMapper.selectById(id);
        device.setDeviceName(deviceName);
        device.setDeviceAddress(deviceAddress);
        device.setDeviceMessageAddress(deviceMessageAddress);
        device.setCommonalityDdress(commonalityDdress);
        device.setAisle(aisle);
        device.setSerialNumber(serialNumber);
            return deviceMapper.updateDeviceById(device);
    }

    @Override
    public List<Device> selectByRoomId(String roomId) {
        return deviceMapper.selectByRoomId(roomId);
    }

    @Override
    public Device selectBydeviceId(String deviceId) {
        return deviceMapper.selectBydeviceId(deviceId);
    }

    @Override
    public PageInfo<Device> getAllDeviceById(Integer pageNum, Integer pageSize, String areaId, String navId, String powerRoomId, String deviceId) {
        List<Device> list = deviceMapper.getAllDeviceById(pageNum, pageSize, areaId, navId, powerRoomId, deviceId);

        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Device> queryByCondition(Integer pageNum, Integer pageSize, String cityId, String projectId, String roomId, String gatewaySn,String token) {
        SysUser sysUser = sysUserMapper.getUserByToken(token);
        if(sysUser!=null){
            if(sysUser.getStatus() == 2 ){
                List<Device> device=deviceMapper.queryByCondition(pageNum,pageSize,cityId,sysUser.getProjectId().toString(),roomId,gatewaySn);
                return   new PageInfo<>(device);
            }
        }
        List<Device> list = deviceMapper.queryByCondition(pageNum, pageSize, cityId, projectId, roomId, gatewaySn);
        return new PageInfo<>(list);
    }


    @Override
    public Device selectByserialNumber(String serialNumber) {
       return  deviceMapper.selectByserialNumber(serialNumber);
    }

    /**
     * 根据配电房Id查询设备
    * */
    @Override
    public List<Device> queryDevice(String roomId) {
        return deviceMapper.queryDevice(roomId);
    }


    @Override
    public Device selectAllBySn(String gatewaySn) {
        return deviceMapper.selectAllBySn(gatewaySn);
    }


    @Override
    public PageInfo<Device> queryDeviceLike(Integer pageNum,Integer pageSize,String text, String token) {
        SysUser sysUser =sysUserMapper.getUserByToken(token);
        if(sysUser!=null){
            if(sysUser.getStatus()==2) {
                return new PageInfo<>(deviceMapper.queryDeviceLike(pageNum,pageSize,text,sysUser.getProjectId().toString()));
            }
        }
        return new PageInfo<>(deviceMapper.queryDeviceLike(pageNum,pageSize,text,null));
    }

    @Override
    public List<Device> queryByDeviceIdLike(String roomId) {
        List<Device> list = deviceMapper.queryByDeviceIdLike(roomId);
        for (Device device : list) {
            device.setSn(device.getSerialNumber());
        }
        return list;
    }

    @Override
    public int selectCountByRoomId(String roomId) {
        return deviceMapper.selectCountByRoomId(roomId);
    }

    private  final  static Logger logger = LoggerFactory.getLogger(DeviceServiceImpl. class);




    /**
     * 多功能表断电报警
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void deviceAlarm() throws Exception{
        List<Gateway> gatewayList =gatewayMapper.getGatewayByBrand(2);
        for (Gateway gateway:gatewayList){
            List<Device> deviceList=deviceMapper.getDeviceAllByGatewaySnAlarmStatus(gateway.getGatewayRemark());
            if (deviceList.size()>0){
                for (Device device:deviceList){
                    Object powerData = redisTemplate.opsForValue().get(device.getSerialNumber());
                    if (powerData==null){
                        if (device.getCommunicationStatus()!= 1){
                          device.setAlarm(device.getAlarm()+1);
                          deviceMapper.updateDeviceAlarmByDeviceId(device.getSerialNumber(),device.getAlarm(),0);

                            if(device.getAlarm() == 10){
                              sendOrdersService.sendOrders(device);
                                /*OrderDelivery orderDelivery = new OrderDelivery();
                                orderDelivery.setOrderDeliveryId(IdUtil.getRandomString(8));
                                orderDelivery.setOrderTypes(1);
                                orderDelivery.setRank(1);
                                orderDelivery.setFault("通讯中断");
                                orderDelivery.setFaultTime(new Date());
                                orderDelivery.setFaultTypes(4);
                                //工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束
                                orderDelivery.setOrderStatus(3);
                                //是否告警 1 告警 2 不告警
                                orderDelivery.setFlag(1);
                                orderDelivery.setAreaId(device.getAreaId());
                                orderDelivery.setAreaName(device.getAreaName());
                                orderDelivery.setProjectId(device.getProjectId());
                                orderDelivery.setProjectName(device.getNavId());
                                orderDelivery.setRoomId(device.getPowerRoomId());
                                orderDelivery.setRoomName(device.getPowerRoomName());
                                orderDelivery.setDeviceId(device.getDeviceId());
                                orderDelivery.setDeviceName(device.getDeviceName());
                                orderDelivery.setDeviceAddress(device.getDeviceAddress());
                                orderDelivery.setSn(device.getSerialNumber());
                                //二次查询redis数据是否存在
                               *//* Thread.sleep(13000);
                                Object powerDatas = redisTemplate.opsForValue().get(device.getSerialNumber());
                                if(powerDatas==null){*//*
                                    int insert = orderDeliveryMapper.insert(orderDelivery);
                                    logger.error(device.getDeviceName()+"断电报警"+ "设备通讯中断" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    deviceMapper.updateDeviceAlarmByDeviceId(device.getDeviceId(),0,1);*/
                                //}
                            }/*else{
                                logger.warn(device.getDeviceName()+"  第一次" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                deviceMapper.updateDeviceAlarmByDeviceId(device.getDeviceId(),1,null);
                            }*/
                        }
                    }else if(powerData != null){
                        //if(device.getCommunicationStatus()==2 || device.getAlarm()==1){
                            deviceMapper.updateDeviceAlarmByDeviceId(device.getSerialNumber(),0,0);
                        //}
                    }
                }
            }
        }
    }


    /**
     * 水浸报警
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void waterInvasion() throws Exception{
            List<WaterInvasion> deviceList=waterInvasionMapper.queryWaterInvasion();
            System.out.println(deviceList);
            if (deviceList.size()>0){
                for (WaterInvasion device:deviceList){
                    Object powerData = redisTemplate.opsForValue().get(device.getWaterlId());
                    if (powerData==null){
                        if (device.getCommunicationStatus()==1){
                            if(device.getAlarm()==1){
                                //二次查询redis数据是否存在
                                Thread.sleep(13000);
                                Object powerDatas = redisTemplate.opsForValue().get(device.getWaterlId());
                                if(powerDatas==null){
                                    logger.error(device.getWaterlId()+"断电报警"+ "设备通讯中断" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    waterInvasionMapper.updateWaterInvasion(2,2,2,device.getWaterlId());
                                }
                            }else{
                                logger.warn(device.getWaterlId()+"  第一次" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                waterInvasionMapper.updateWaterInvasion(1,null,1,device.getWaterlId());
                            }
                        }
                    }else {
                        if(device.getCommunicationStatus()==2 || device.getAlarm()==1){
                            waterInvasionMapper.updateWaterInvasion(0,1,1,device.getWaterlId());
                        }
                    }
                }
            }
    }


    /**
     * 电压表报警
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void voltage() throws Exception{
        List<Voltage> deviceList=voltageMapper.queryVoltage();
        System.out.println(deviceList);
        if (deviceList.size()>0){
            for (Voltage device:deviceList){
                Object powerData = redisTemplate.opsForValue().get(device.getVoltageId());
                if (powerData==null){
                    if (device.getCommunicationStatus()==1){
                        if(device.getAlarm()==1){
                            //二次查询redis数据是否存在
                            Thread.sleep(13000);
                            Object powerDatas = redisTemplate.opsForValue().get(device.getVoltageId());
                            if(powerDatas==null){
                                logger.error(device.getVoltageId()+"断电报警"+ "设备通讯中断" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                voltageMapper.updateVoltage(2,2,2,device.getVoltageId());
                            }
                        }else{
                            logger.warn(device.getVoltageId()+"  第一次" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            voltageMapper.updateVoltage(1,null,1,device.getVoltageId());
                        }
                    }
                }else {
                    if(device.getCommunicationStatus()==2 || device.getAlarm()==1){
                        voltageMapper.updateVoltage(0,1,1,device.getVoltageId());
                    }
                }
            }
        }
    }




    @Override
    public List<LoopType> queryLoopType(String projectId) {
        List<LoopType> list = loopTypeMapper.queryLoopType();
        String sumPowerData = incomingCabinetMapper.getSumPowerDataByProjectId(projectId);
        if(sumPowerData==null){
            sumPowerData="1";
        }

        List<LoopType> ll=new ArrayList();
        List<Device> devices=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");

        float illumination=0;
        float sum=0;
        String illuminations="";

        if(list.size()!=0){
            for (LoopType loopType : list) {
                devices=deviceMapper.queryTypeId(projectId,loopType.getTypeId());
                illumination=0;
                illuminations="";
                if(devices.size()!=0){
                    for (Device device : devices) {
                        Object object = redisTemplate.opsForValue().get(device.getSerialNumber());
                        ObjectMapper objectMapper = new ObjectMapper();
                        Powerdata powerData = objectMapper.convertValue(object, Powerdata.class);
                        if(powerData!=null){
                            illumination=illumination+powerData.getForwardActiveTotalElectricalEnergy();
                        }else {
                            illumination=illumination+0;
                        }
                    }
                    loopType.setPowerData(illumination);
                    sum=sum+illumination/Float.parseFloat(sumPowerData);
                    illuminations=df.format(illumination/Float.parseFloat(sumPowerData));
                    illuminations = illuminations.substring(0, illuminations.length() - 1);

                    loopType.setValue(illuminations);
                    ll.add(loopType);
                }
            }
                String sums = df.format(1 - sum);
                sums = sums.substring(0, sums.length() - 1);
                LoopType loopType = new LoopType();
                loopType.setTypeName("其他");
                loopType.setValue(sums);
                loopType.setPowerData(Float.parseFloat(sumPowerData));
                ll.add(loopType);
        }
        return ll;
    }

    @Override
    public List<LoopType> queryYearLoopType(String projectId,String createTime) {
        List<LoopType> list = loopTypeMapper.queryLoopType();
        String sumPowerData = incomingCabinetMapper.queryYearPowerDataByRprojectId(projectId,createTime);
        if(sumPowerData==null){
            sumPowerData="1";
        }

        List<LoopType> ll=new ArrayList();
        List<Device> devices=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");

        float illumination=0;
        float sum=0;
        String illuminations="";

        if(list.size()!=0){
            for (LoopType loopType : list) {
                devices=deviceMapper.queryTypeId(projectId,loopType.getTypeId());
                illumination=0;
                illuminations="";
                if(devices.size()!=0){
                    for (Device device : devices) {
                        String data = powerdataMapper.queryYearLoopType(device.getSerialNumber(),createTime);
                        if(data!=null){
                            illumination=illumination+Float.parseFloat(data);
                        }else {
                            illumination=illumination+0;
                        }
                    }
                    loopType.setPowerData(illumination);
                    sum=sum+illumination/Float.parseFloat(sumPowerData);
                    illuminations=df.format(illumination/Float.parseFloat(sumPowerData));
                    illuminations = illuminations.substring(0, illuminations.length() - 1);

                    loopType.setValue(illuminations);
                    ll.add(loopType);
                }
            }
            String sums = df.format(1 - sum);
            sums = sums.substring(0, sums.length() - 1);
            LoopType loopType = new LoopType();
            loopType.setTypeName("其他");
            loopType.setValue(sums);
            loopType.setPowerData(Float.parseFloat(sumPowerData));
            ll.add(loopType);
        }
        return ll;
    }

    @Override
    public List<LoopType> queryMonthLoopType(String projectId,String createTime) {
        List<LoopType> list = loopTypeMapper.queryLoopType();
        String sumPowerData = incomingCabinetMapper.queryMonthPowerDataByRprojectId(projectId,createTime);
        if(sumPowerData==null){
            sumPowerData="1";
        }

        List<LoopType> ll=new ArrayList();
        List<Device> devices=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00%");

        float illumination=0;
        float sum=0;
        String illuminations="";

        if(list.size()!=0){
            for (LoopType loopType : list) {
                devices=deviceMapper.queryTypeId(projectId,loopType.getTypeId());
                illumination=0;
                illuminations="";
                if(devices.size()!=0){
                    for (Device device : devices) {
                        String data = powerdataMapper.queryMonthLoopType(device.getSerialNumber(),createTime);
                        if(data!=null){
                            illumination=illumination+Float.parseFloat(data);
                        }else {
                            illumination=illumination+0;
                        }
                    }
                    loopType.setPowerData(illumination);
                    sum=sum+illumination/Float.parseFloat(sumPowerData);
                    illuminations=df.format(illumination/Float.parseFloat(sumPowerData));
                    illuminations = illuminations.substring(0, illuminations.length() - 1);

                    loopType.setValue(illuminations);
                    ll.add(loopType);
                }
            }
            String sums = df.format(1 - sum);
            sums = sums.substring(0, sums.length() - 1);
            LoopType loopType = new LoopType();
            loopType.setTypeName("其他");
            loopType.setValue(sums);
            loopType.setPowerData(Float.parseFloat(sumPowerData));
            ll.add(loopType);
        }
        return ll;
    }

    @Override
    public List<Device> getDeviceByProjectId(String token) {
        List list = new ArrayList<>();
        List list1 = new ArrayList<>();
        SysUser user = sysUserMapper.getUserByToken(token);
        if(user!=null){
            if(user.getProjectId() != null){
                Project project = projectMapper.queryProjectByProId(user.getProjectId().toString());
                if(project != null){
                    if(user.getStatus()==2) {
                        if("1".equals(project.getPowerDaraFlag())){
                            list = deviceMapper.getDeviceByProjectId(project.getProjectId());
                        }else if("2".equals(project.getPowerDaraFlag())){
                            list = temperatureDeviceMapper.getTemperatureDeviceListByProjectId(project.getProjectId());
                        }else if("0".equals(project.getPowerDaraFlag())){
                            list = deviceMapper.getDeviceByProjectId(project.getProjectId());
                            list1 = temperatureDeviceMapper.getTemperatureDeviceListByProjectId(project.getProjectId());
                            for (Object o : list1) {
                                list.add(o);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        float[] realArr2 = {0, 1, 2, 3, 4, 5};
        for (int i = 0; i < realArr2.length; i++) {
            if(i < 3){
                System.out.println(realArr2[i]);
            }
        }
    }

    @Override
    public List queryFacility() {
        List<Device> list = deviceMapper.selectByRoomId("53088054");
        List  PowerRoomIdList = new ArrayList<>();
        list.forEach(PowerRoomId -> {
            Object object = redisTemplate.opsForValue().get(PowerRoomId.getSerialNumber());
            PowerRoomIdList.add(object);
        });
        return PowerRoomIdList;
    }
}
